<template>
  <div>
    <div v-if="(!edit)||(!field.name)">
      <div v-if="value.cval!==null&&value.cval.startsWith('http://','https://')">
        <div @click="toRescue(value.cval)"> 打开</div>
        <div @click="openExternal(value.cval)"> 浏览器打开</div>
      </div>
      <div v-else>{{ value.cval }}</div>
    </div>
    <div v-else style="border: #0d99a5;border-width: 2px">
      <Field
        v-model="newval"
        :title="field.title"
        :placeholder="placeholder||'请输入'+title"
        @input="onchange"
      />
    </div>

  </div>
</template>

<script>
  import Vue from 'vue'
  import gql from 'graphql-tag'
  import {Field} from "vant"

  export default {
    name: 'Char',
    components: {Field},
    props: {
      field: {
        type: Object,
        default() {
          return {cval: ''}
        }
      },
      model: {type: String, default: ''},
      id: {type: Number, default: 0},
      'showClear': {type: Boolean},
      'placeholder': {type: String, default: '请输入'},
      edit: {type: Boolean, default: false},
      saveFast: {type: Boolean, default: true}
    },
    inject: ['getValue'],
    data: function () {
      return {newval: this.getValue().cval}
    },
    mounted: function () {
    },
    watch: {},
    computed: {
      value() {
        return this.getValue()
      },
      writeDict() {
        let v = {}
        v[this.field.name] = this.newval
        return v
      }
    },
    methods: {
      onchange: function (val) {
        if (this.saveFast) {
          this.$apollo.mutate({
            mutation: gql`mutation($id:Int!,$model:String!,$value:JSON!){
  writeRecord(id:$id,model:$model,value:$value){
    ok
  }
}`,
            variables: {id: this.id, model: this.model, value: this.writeDict}
          }).then(function (response) {
            if (response && response.data.writeRecord.ok) {
              // self.app_root.toast(response.result.errMsg)
              // self.$router ? self.$router.back() : window.history.back()
            } else if (response && !response.data.writeRecord.ok) {
              // self.app_root.toast(response.result.errMsg)
            }
          })
            .catch(function (error) {
              console.log(error, __filename)
            })
        } else {
          Vue.set(this.value, 'newval', this.newval)
          Vue.set(this.value, 'change', this.value.cval !== this.newval)
        }
      },
      toRescue(url) {
        window.location.href = url
      },
      openExternal(url) {
        ipcRender.send('open-url', url)
      }
    }
  }
</script>
<style scoped>

</style>
